package util

import (
	"bufio"
	"container/list"
	"database/sql"
	"fmt"
	"io"
	"strconv"
	"strings"
)

type Command struct{
	TimeStamp  int64
	CommandStr string
	Session string
	Resp *[]byte
}

func WriteString(fileObj io.Writer,content string)  {
	writeObj := bufio.NewWriterSize(fileObj,4096)
	//
	if _,err := writeObj.WriteString(content);err != nil {
		fmt.Println("error.",content)
	}
	writeObj.Flush()
}

func ReadLine(bfRd *bufio.Reader) (*Command,error) {
	for{
		line, err := bfRd.ReadBytes('\n')
		str := String(line)
		if strings.HasPrefix(str,"session:10.204.8.220:53057"){
			strItems := strings.Split(str,":")
			command := new(Command)
			command.TimeStamp,_ = strconv.ParseInt(strings.Replace(strItems[3],"\n","",1),0,64)
			for{
				line, err = bfRd.ReadBytes('\n')
				str = String(line)
				if strings.HasPrefix(str,"session:"){
					break
				}
				command.CommandStr = command.CommandStr +str
			}

			return command,nil
		}
		if err != nil {
			if err == io.EOF {
				return nil,nil
			}
			return nil,err
		}
	}


	return nil,nil
}

func ReadMap(bfRd *bufio.Reader)(*map[string] *sql.DB,*list.List,int64,int64)  {
	beginTime :=int64(0)
	endTime := int64(0)
	readMap := make(map[string] *sql.DB)
	lst := list.New()
	command := new(Command)
	command = nil
	for{
		line, err := bfRd.ReadBytes('\n')
		if err != nil {
			break
		}
		str2 := String(line)
		str := ReplacePay(str2)
		if strings.HasPrefix(str,"session:"){
			strItems := strings.Split(str,":")
			key := strItems[1] + ":" + strItems[2]
			if command == nil{
				beginTime,_ = strconv.ParseInt(strings.Replace(strItems[3],"\n","",1),0,64)
			}

			command = new(Command)
			command.TimeStamp,_ = strconv.ParseInt(strings.Replace(strItems[3],"\n","",1),0,64)
			command.Session = key
			lst.PushBack(command)
			if _, ok := readMap[key]; !ok {
				readMap[key] = nil
			}
		}else {
			command.CommandStr = command.CommandStr +str
		}
	}
	endTime = command.TimeStamp
	return &readMap,lst,beginTime,endTime
}